import { TLoginCheck, TResponseLogin, TResponseUserInfo } from '@/api/sys/type'
import { loginCheck, getUserInfo, userLogout } from '@/api/sys/user'
import router from '@/router'
import { ICtx, IUserState } from '@/typings'
import { removeToken } from '@/utils/cookie'
import { mapMenu, groupMenu } from '@/utils/filterData'
import { SET_TOKEN, SET_MENU_LIST, SET_USER_INFO } from './actionTypes'

export default {
  login({ commit }: ICtx<IUserState>, form: TLoginCheck): Promise<TResponseLogin> {
    return new Promise((resolve) => {
      loginCheck(form).then((res: TResponseLogin) => {
        if (res.state) {
          commit(SET_TOKEN, res.result.token)
        }
        resolve(res)
      })
    })
  },
  refreshUser({ commit, dispatch }: ICtx<IUserState>): Promise<TResponseUserInfo> {
    const rootCommonLoading = (isLoading = false) => dispatch('common/toggleLoading', isLoading, { root: true })

    rootCommonLoading(true)
    return new Promise((resolve) => {
      getUserInfo().then((res: TResponseUserInfo) => {
        const { menuEntityList } = res.result
        const menuList = mapMenu(groupMenu(menuEntityList, '0'))
        commit(SET_MENU_LIST, menuList)

        commit(SET_USER_INFO, res.result)

        menuList.forEach((menus) => router.addRoute(menus))

        rootCommonLoading(false)
        resolve()
      })
    })
  },
  logout({ commit }: ICtx<IUserState>): void {
    userLogout().then(() => {
      removeToken()
      commit(SET_TOKEN, '')
      commit(SET_MENU_LIST, [])
      commit(SET_USER_INFO, {})
      router.replace('/login')
    })
  }
}
